package org.qiyu.live.im.core.server.handler.impl;

import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.common.ImMsgCodeEnum;
import org.qiyu.live.im.core.server.handler.ImHandlerFactory;
import org.qiyu.live.im.core.server.handler.SimpleHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description: 使用一个map对象管理所有的handler
 * User: sfx
 * Date: 2023-10-07
 * Time: 16:54
 */
@Component
public class ImHandlerFactoryImpl implements ImHandlerFactory, InitializingBean {

    @Resource
    private ApplicationContext applicationContext;

    private static final Map<Integer, SimpleHandler> map = new HashMap<>();

    @Override
    public void doHandler(ChannelHandlerContext ctx, ImMsg msg) {
        // 必须是im的消息
        SimpleHandler simpleHandler = map.get(msg.getCode());
        if (simpleHandler == null) {
            throw new IllegalArgumentException("simpleHandler is error code is " + msg.getCode());
        }
        // 执行对应的handler
        simpleHandler.handler(ctx, msg);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化
        map.put(ImMsgCodeEnum.IM_LOGIN_MSG.getCode(), applicationContext.getBean(LoginMsgHandler.class));
        map.put(ImMsgCodeEnum.IM_LOGOUT_MSG.getCode(), applicationContext.getBean(LogoutMsgHandler.class));
        map.put(ImMsgCodeEnum.IM_BIZ_MSG.getCode(), applicationContext.getBean(BizMsgHandler.class));
        map.put(ImMsgCodeEnum.IM_HEARTBEAT_MSG.getCode(), applicationContext.getBean(HeartBeatMsgHandler.class));
        map.put(ImMsgCodeEnum.IM_ACK_MSG.getCode(), applicationContext.getBean(ACKMsgHandler.class));
    }
}